package com.wenli.lt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wenli.lt.entity.*;
import com.wenli.lt.entity.po.GoodOrderPo;
import com.wenli.lt.entity.po.goodsVo;
import com.wenli.lt.mapper.*;
import com.wenli.lt.service.IImgService;
import com.wenli.lt.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenli.lt.util.OSSClientUtil;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lt
 * @since 2021-03-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private CollegeMapper collegeMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private InformationMapper informationMapper;
    @Autowired
    private FansMapper fansMapper;

    @Autowired
    private GoodsMapper goodsMapper;


    @Autowired
    private OSSClientUtil ossClient;
    @Autowired
    private CommentlistMapper commentlistMapper;
    @Autowired
    IImgService iImgService;

    @Override
    public Map getUserInfo(String studentNumber) {
        Map map = new HashMap();
        //粉丝
        QueryWrapper<Fans>  fansQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Fans>  fansQueryWrapper1 = new QueryWrapper<>();
        User user = userMapper.selectByIdInfo(studentNumber);
        Classes classes = classMapper.selectById(user.getClasses());
        Grade  grade = gradeMapper.selectById(user.getGrade());
        College college = collegeMapper.selectById(user.getCollege());
        //关注
        fansQueryWrapper.eq("focusId",studentNumber);
        fansQueryWrapper1.eq("befocusId",studentNumber);
        Integer integer = fansMapper.selectCount(fansQueryWrapper);
        Integer integer1 = fansMapper.selectCount(fansQueryWrapper1);
        map.put("fansCount",integer1);
        map.put("beFansCount",integer);
        map.put("user",user);
        //消息
        QueryWrapper<Information>  informationQueryWrapper = new QueryWrapper<>();
        informationQueryWrapper.eq("beSendStudentNumber",studentNumber);
        Integer integer2 = informationMapper.selectCount(informationQueryWrapper);
        map.put("notReadCount",integer2);
        //我发布的
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("sellerstudentNumber",studentNumber);
        List<Goods> goods = goodsMapper.selectList(goodsQueryWrapper);
        map.put("goods",goods);
        map.put("grade",grade);
        map.put("college",college);
        map.put("classes",classes);
        return map;
    }

    @Override
    public User login(String studentNumber, String password, Integer status) {
        QueryWrapper<User>  queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentNumber",studentNumber);
        queryWrapper.eq("password",password);
        queryWrapper.eq("jurisdiction",status);
        queryWrapper.eq("isLogin",0);
//        if (status == 0){
////            queryWrapper.select("userName");
//        }else {
////            queryWrapper.select("studentNumber","userName","nickName","avater");
//        }
        return userMapper.selectOne(queryWrapper);

    }

    @Override
    public Boolean UpdatePassword(String studentNumber, String oldPassword, String newPassword) {
        QueryWrapper<User>  queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentNumber",studentNumber);
        queryWrapper.eq("password",oldPassword);
        queryWrapper.eq("isLogin",0);
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(user)){
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("password",newPassword);
            user.setPassword(newPassword);
            //todo  代码信息
            userMapper.UpdatePassword(user.getStudentNumber(),user.getPassword());
            return true;
        }else {
            return false;
        }
    }
    @Override
    public Boolean updateUserInfo(String studentNumber, String nickname, String phoneNumber,String avater) {
        QueryWrapper<User>  queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentNumber",studentNumber);
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(user)){
            if (!StringUtils.isBlank(nickname)){
                user.setNickname(nickname);

            }
            if (!StringUtils.isBlank(phoneNumber)){
                user.setPhoneNumber(phoneNumber);

            }
            if (!StringUtils.isBlank(avater)){
                user.setAvater(avater);

            }
                userMapper.updateById(user);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Menu> getTree(Integer stauts) {
//        colleges 集合

        QueryWrapper<Grade> gradeName = new QueryWrapper<>();
        gradeName.select().orderByAsc("gradeName");
        List<Grade> grades = gradeMapper.selectList(gradeName);
        Boolean b = true;
        List<Menu> menus = new ArrayList<>();
        for (Grade grade:grades) {
            if (stauts != null && stauts == 0 ){
                b =false;
            }
            menus.add(new Menu(grade.getGradeId(),grade.getGradeName(),b,null));
        }
        if (stauts == null || stauts == 1){
            List<College> colleges = collegeMapper.selectList(new QueryWrapper<>());
            if (stauts != null && stauts == 1){
                b =false;
            }
            for (College college:colleges) {
                menus.add(new Menu(college.getCollegeId(),college.getCollegeName(),b,college.getGradeId()));
            }
        }

        if (stauts == null){
            List<Classes> classesList = classMapper.selectList(new QueryWrapper<>());
            for (Classes  classes:classesList ) {
                menus.add(new Menu(classes.getClassId(),classes.getClassName(),false,classes.getCollegeId()));
            }
        }
        //获取父节点
        List<Menu> collect = menus.stream().filter(m -> m.getParentId()==null).map(
                (m) -> {
                    m.setChildren(getChildrens(m, menus));
                    return m;
                }
        ).collect(Collectors.toList());
        return collect;
    }

    @Override
    public IPage<User> getPeopleList(String classId, String collegeId, String gradeId, Long page, Long size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("jurisdiction",1);
        if (!StringUtils.isBlank(classId)){
            queryWrapper.eq("classes",classId);
        }
        if (!StringUtils.isBlank(collegeId)){
            queryWrapper.eq("college",collegeId);
        }
        if (!StringUtils.isBlank(gradeId)){
            queryWrapper.eq("grade",gradeId);
        }
        return  userMapper.selectPage(new Page<>(page,size),queryWrapper);
    }
    @Override
    public IPage getGoodLy(String studentNumber, Integer type, Long page, Long size) {
        if (type == 1){
          IPage page1=  commentlistMapper.selectcommentPage(new Page(page,size),studentNumber);
          return page1;
        }else if (type == 2){
            QueryWrapper<Information> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("beSendStudentNumber",studentNumber);
            IPage page1=  informationMapper.selectPage(new Page(page,size),queryWrapper);
            return page1;
        }else {
            return null;
        }
    }

    /**
     *
     * @param files
     * @param
     * @return
     * @throws IOException
     */
    public List<String>  updateHead(MultipartFile[] files,String goodsId) throws IOException {
        List<String> picUrl =  new ArrayList<>();
        for (MultipartFile file:files
             ) {
            if (file == null || file.getSize() <= 0) {
                throw new IOException("图片不能为空");
            }
            String name = ossClient.uploadImg2Oss(file);
            picUrl.add("http://zouyuan-test.oss-cn-qingdao.aliyuncs.com/gzdt/img/"+name);
        }

        if (!StringUtils.isBlank(goodsId)){
          iImgService.saveGoodsImg(goodsId,picUrl);

        }

        return picUrl;
    }

    @Override
    public Boolean addUser(User user) {
        String classId = user.getClasses();
        Classes classes = classMapper.selectById(classId);
        user.setCollege(classes.getCollegeId());
        user.setGrade(classes.getGradeId());
        user.setIsLogin(0);
        return 1 ==  userMapper.insert(user);
    }

    @Override
    public Boolean deleteUser(String studentNumber) {

        return 1 == userMapper.deleteById(studentNumber);
    }

    @Override
    public Boolean setUserLoginRelease(String studentNumber, Integer isLogin, Integer isRelease) {
        User user = userMapper.selectById(studentNumber);
        if (isLogin != null){
            user.setIsLogin(isLogin);
        }

        if (isRelease != null){
            user.setIsRelease(isRelease);
        }
        return 1==userMapper.updateById(user);
    }

    @Override
    public Map getUserInfoByStudentNumber(String studentNumber) {
        Map map = new HashMap();
        User user = userMapper.selectByIdInfo(studentNumber);
        Classes classes = classMapper.selectById(user.getClasses());
        Grade  grade = gradeMapper.selectById(user.getGrade());
        College college = collegeMapper.selectById(user.getCollege());
        map.put("user",user);
        //我发布的
        List<goodsVo> goods = goodsMapper.getGoods(studentNumber);
        map.put("goods",goods);
        // 我 购买的
        List<GoodOrderPo> buyGoodList = goodsMapper.getBuyGoodList(studentNumber);
        map.put("buyGoods",buyGoodList);
        // 待卖出的
        List<GoodOrderPo> noBuyGoodList = goodsMapper.getNoBuyGoodList(studentNumber);
        // 购物车
        List<GoodOrderPo> wantbuyGoodList = goodsMapper.wantuyGoodList(studentNumber);
        map.put("noBuyGoods",noBuyGoodList);
        map.put("grade",grade);
        map.put("wantbuyGood",wantbuyGoodList);
        map.put("college",college);
        map.put("classes",classes);

        return map;
    }



    /**
     * 递归查询子节点
     * @param root  根节点
     * @param all   所有节点
     * @return 根节点信息
     */
    private List<Menu> getChildrens(Menu root, List<Menu> all) {
        List<Menu> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), root.getId());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }





}
